package com.hxh.ocr;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifInteropDirectory;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImageUtils {
    /**
     * @author HXH
     * @description:
     * @date  2024/3/4
     * @param image: 图片缩小
     * @param width:
     * @param height:
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage smallerImage(BufferedImage image, int width, int height) {
        if (width < Ocr.ID_CARD_WIDTH * 2 || height < Ocr.ID_CARD_HEIGHT * 2) {
            return image;
        }
        long begin = System.currentTimeMillis();
        int widthPercent = width / Ocr.ID_CARD_WIDTH;
        int heightPercent = height / Ocr.ID_CARD_HEIGHT;
        int resPercent = Math.min(widthPercent, heightPercent);

        int smallWidth = width / resPercent;
        int smallHeight = height / resPercent;

        BufferedImage smallImage = new BufferedImage(smallWidth, smallHeight, BufferedImage.TYPE_3BYTE_BGR);
        for (int x = 0, sx = 0; sx < smallWidth && x < width; x += resPercent, sx++) {
            for (int y = 0, sy = 0; sy < smallHeight && y < height; y += resPercent, sy++) {
                int argb = image.getRGB(x, y);
                smallImage.setRGB(sx, sy, argb);
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("图片缩小倍数：" + resPercent + "  耗时ms：" + (end - begin));
        return smallImage;

    }

    /**
     * @author HXH
     * @description:   加深图片颜色
     * @date  2024/3/4
     * @return void
     **/
    public static void deeperImageColor(BufferedImage image, int width, int height) {
        int deepColorFlag = 250;
        int subColor = 150;
        for (int x = 2; x < width-2; x+=2) {
            for (int y = 2; y < height-2; y+=2) {
                Object data = image.getRaster().getDataElements(x, y, null);
                int red = image.getColorModel().getRed(data);
                int green = image.getColorModel().getGreen(data);
                int blue = image.getColorModel().getBlue(data);

                if (red < deepColorFlag && blue < deepColorFlag && green < deepColorFlag){

                    Object up = image.getRaster().getDataElements(x, y-1, null);
                    int upred = image.getColorModel().getRed(up);
                    int upgreen = image.getColorModel().getGreen(up);
                    int upblue = image.getColorModel().getBlue(up);
                    if (upred > deepColorFlag || upgreen > deepColorFlag || upblue > deepColorFlag){
                        continue;
                    }
                    Object down = image.getRaster().getDataElements(x, y+1, null);
                    int downred = image.getColorModel().getRed(down);
                    int downgreen = image.getColorModel().getGreen(down);
                    int downblue = image.getColorModel().getBlue(down);
                    if (downred > deepColorFlag || downgreen > deepColorFlag || downblue > deepColorFlag){
                        continue;
                    }

                    Object left = image.getRaster().getDataElements(x-1, y, null);
                    int leftred = image.getColorModel().getRed(left);
                    int leftgreen = image.getColorModel().getGreen(left);
                    int leftblue = image.getColorModel().getBlue(left);
                    if (leftred > deepColorFlag || leftgreen > deepColorFlag || leftblue > deepColorFlag){
                        continue;
                    }

                    Object right = image.getRaster().getDataElements(x+1, y, null);
                    int rightred = image.getColorModel().getRed(right);
                    int rightgreen = image.getColorModel().getGreen(right);
                    int rightblue = image.getColorModel().getBlue(right);
                    if (rightred > deepColorFlag || rightgreen > deepColorFlag || rightblue > deepColorFlag){
                        continue;
                    }

                    Color dataColor = new Color(
                            red>subColor?red-subColor:0,
                            green>subColor?green-subColor:0,
                            blue>subColor?blue-subColor:0);
                    image.setRGB(x, y, dataColor.getRGB());
                }
            }
        }
    }

    /**
     * 获取图片正确显示需要旋转的角度（顺时针）
     *
     * @param filePath
     * @return
     */
    public static int getRotateAngleForPhoto(String filePath) {
        File file = new File(filePath);
        int angle = 0;
        Metadata metadata;
        try {
            metadata = JpegMetadataReader.readMetadata(file);
            Iterable<Directory> directories = metadata.getDirectories();
            metadata.getFirstDirectoryOfType(ExifInteropDirectory.class);
            for (Directory directory : directories) {
                if ("Exif IFD0".equals(directory.getName())) {
                    Collection<Tag> tags = directory.getTags();
                    for (Tag tag : tags) {
                        if ("Orientation".equals(tag.getTagName())) {
                            angle = getNum(tag.getDescription());
                            break;
                        }
                    }
                    break;
                }
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return angle;
    }

    /**
     * 旋转照片
     *
     * @param fullPath
     * @param angel
     * @return
     */
    public static String rotatePhonePhoto(String fullPath, String descPath, int angel) {
        BufferedImage src;
        try {
            src = ImageIO.read(new File(fullPath));
            int src_width = src.getWidth(null);
            int src_height = src.getHeight(null);
            int swidth = src_width;
            int sheight = src_height;
            if (angel == 90 || angel == 270) {
                swidth = src_height;
                sheight = src_width;
            }
            Rectangle rect_des = new Rectangle(new Dimension(swidth, sheight));
            BufferedImage res = new BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = res.createGraphics();
            g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);
            g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
            g2.drawImage(src, null, null);
            ImageIO.write(res, "jpg", new File(descPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fullPath;
    }

    private static int getNum(String str) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String numStr = m.replaceAll("").trim();
        if (StringUtils.isNotBlank(numStr)) {
            return Integer.valueOf(numStr);
        } else {
            return 0;
        }
    }

    /**
     * 处理ios照片
     *
     * @param filePath
     */
    public static void processIosPhotos(String filePath) {
        // 计算旋转的角度
        int angle = getRotateAngleForPhoto(filePath);
        if (angle != 0) {
//            rotatePhonePhoto(filePath, angle);
        }
    }


    public static void main(String[] args) throws Exception {
//        String filePath = "C:\\Users\\lenovo\\Desktop\\orcPicture\\aaa.jpg";
        String filePath = "C:\\Users\\lenovo\\Desktop\\orcPicture\\s8.jpgrotate270.jpg";
//        int angle = getRotateAngleForPhoto(filePath);
//        System.out.println("旋转角度:" + angle);
//        rotatePhonePhoto(filePath, angle);

//        checkEdge("Roberts边缘检测",filePath);

        BufferedImage bufferedImage = ImageFilter.cloneImage(ImageIO.read(new File(filePath)));
        getIDCardX(bufferedImage);
    }


    /**
     * @author HXH
     * @description:   在一张图片中，提取出身份证图片，注意，身份证在图片中不能是斜的！！！
     * @date  2024/3/1
     * @param bufferedImage: 截取的身份证图片 提取失败，返回原图
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage fetchIDCardFromImage(BufferedImage bufferedImage) {
        try {
            long begin = System.currentTimeMillis();
            List<Integer> xlist = getIDCardX(bufferedImage);
            int width = xlist.get(1) - xlist.get(0);
            if (width < 400) {
                System.out.println("提取身份证失败，返回原图");
                return bufferedImage;
            }
            List<Integer> ylist = getIDCardY(bufferedImage);
            int height = ylist.get(1) - ylist.get(0);
            if (height < 200) {
                System.out.println("提取身份证失败，返回原图");
                return bufferedImage;
            }
            BufferedImage res = ImageFilter.subImage(bufferedImage, xlist.get(0), ylist.get(0), width, height);
//            ImageIO.write(res, "jpg", new FileOutputStream("C:\\Users\\lenovo\\Desktop\\orcPicture\\after\\sub.jpg"));
            long end = System.currentTimeMillis();
            System.out.println("提取图片耗时ms：" + (end - begin));
            return res;
        } catch (Exception e) {
            System.out.println("提取身份证失败，返回原图");
            return bufferedImage;
        }
    }


    //检测像素的宽度
    //检测附近的像素点 对于检测x轴而言，就是x轴左右两侧的数量，对于检测y轴而言，就是上下两侧的数量
    private static int checkNearPixel = 3;
    //颜色前后相差XXXX，就认为是边缘   宽度 * rgb的最少色差2 * r g b三个因子（三个可能不会全部都变，所有选2，留点容错）
    private static int colorMinDiff = checkNearPixel * 2 * 2;


    /**
     * @param image:
     * @param x:     当前像素点的x轴坐标
     * @param y:     当前像素点的y轴坐标
     * @return boolean
     * @author HXH
     * @description: 检测当前像素点是否处于边缘 x轴专用
     * @date 2024/3/1
     **/
    public static boolean getIDCardXCheck(BufferedImage image, int x, int y) {
        int leftRedCount = 0;
        int leftGreen = 0;
        int leftBlue = 0;
        for (int i = 1; i < checkNearPixel; i++) {
            Object data1 = image.getRaster().getDataElements(x - i, y, null);
            int dataRed1 = image.getColorModel().getRed(data1);
            int dataBlue1 = image.getColorModel().getBlue(data1);
            int dataGreen1 = image.getColorModel().getGreen(data1);

            leftRedCount += dataRed1;
            leftBlue += dataBlue1;
            leftGreen += dataGreen1;
        }

        int rightRedCount = 0;
        int rightGreen = 0;
        int rightBlue = 0;
        for (int i = 1; i < checkNearPixel; i++) {
            Object data1 = image.getRaster().getDataElements(x + i, y, null);
            int dataRed1 = image.getColorModel().getRed(data1);
            int dataBlue1 = image.getColorModel().getBlue(data1);
            int dataGreen1 = image.getColorModel().getGreen(data1);
            rightRedCount += dataRed1;
            rightBlue += dataBlue1;
            rightGreen += dataGreen1;
        }

        if ((Math.abs(leftRedCount - rightRedCount) +
                Math.abs(leftGreen - rightGreen) +
                Math.abs(leftBlue - rightBlue) > colorMinDiff)) {
            return true;
        }
        return false;
    }

    /**
     * @param bufferedImage:
     * @return java.util.List<java.lang.Integer> x轴的两个值
     * @author HXH
     * @description: 识别图片的中，身份证x轴边缘
     * @date 2024/3/1
     **/
    public static List<Integer> getIDCardX(BufferedImage bufferedImage) {
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        System.out.println("图片宽度：" + width);
        System.out.println("图片高度" + height);

        int splitXCount = 0;
        //连续x个像素都是边缘，则认为就是x这一列就是边缘
        int splitXMinCount = height / 2 / 40;
        splitXMinCount = Math.max(splitXMinCount, 25);
        System.out.println("splitXMinCount: " + splitXMinCount);

        List<Integer> xEdge = new ArrayList<>();
        int maxHeight = height - checkNearPixel;
        for (int x = checkNearPixel, maxWidth = width - checkNearPixel; x < maxWidth; x += 2) {
            //这个5与身份证在图片中的倾斜角度有关，身份证越倾斜，这个值需要越小，耗时越长
            //是不是越小，精度越高？是的，但是也要考虑到后面身份证识别时，如果倾角过大，可能截取失败
            //如果倾角过大，ocr识别失败
            for (int y = checkNearPixel; y < maxHeight; y += 5) {
                if (getIDCardXCheck(bufferedImage, x, y)) {
                    splitXCount++;
                    if (splitXCount > splitXMinCount) {
                        xEdge.add(x);
//                            System.out.println("边缘检测....x:" + x + "   y:" + y);
                    }
                } else {
                    splitXCount = 0;
                }
            }
        }

        Map<Integer, Integer> confidence2X = new HashMap<>();
        int confidence = 0;
        int confidenceX = xEdge.get(0);
        int maxCountConfidence = Math.min(width / 90,100);
        for (int i = 1; i < xEdge.size(); i++) {
            int temp = xEdge.get(i);
            if (temp - confidenceX <= maxCountConfidence) {
                confidence++;
            } else {
                System.out.println("边缘x:" + confidenceX + " 置信度：" + confidence);
                confidence2X.put(confidenceX, confidence);
                confidenceX = temp;
                confidence = 0;
            }
        }
        confidence2X.put(confidenceX, confidence);
//        long end = System.currentTimeMillis();
        System.out.println("边缘x:" + confidenceX + " 置信度：" + confidence);

        //取出置信度最高的两个值
        List<Integer> res = new ArrayList<>(2);
        List<Integer> keys = new ArrayList<>(confidence2X.values());
        keys.sort((a, b) -> b - a);
        keys = keys.subList(0, 2);
        for (Integer integer : confidence2X.keySet()) {
            for (int i = 0; i < keys.size(); i++) {
                if (confidence2X.get(integer).equals(keys.get(i))) {
                    res.add(integer);
                    break;
                }
                if (res.size() >= 2) {
                    break;
                }
            }
            if (res.size() >= 2) {
                break;
            }
        }
        res.sort(Comparator.comparingInt(a -> a));
        System.out.println("识别身份证x轴位置：" + res.get(0));
        System.out.println("识别身份证x轴位置：" + res.get(1));
        return res;
    }

    /**
     * @param image:
     * @param x:     当前像素点的x轴坐标
     * @param y:     当前像素点的y轴坐标
     * @return boolean
     * @author HXH
     * @description: 检测当前像素点是否处于边缘 y轴专用
     * @date 2024/3/1
     **/
    public static boolean getIDCardYCheck(BufferedImage image, int x, int y) {
        int upRedCount = 0;
        int upGreen = 0;
        int upBlue = 0;
        for (int i = 1; i < checkNearPixel; i++) {
            Object data1 = image.getRaster().getDataElements(x, y - i, null);
            int dataRed1 = image.getColorModel().getRed(data1);
            int dataBlue1 = image.getColorModel().getBlue(data1);
            int dataGreen1 = image.getColorModel().getGreen(data1);
            upRedCount += dataRed1;
            upBlue += dataBlue1;
            upGreen += dataGreen1;
        }


        int downRedCount = 0;
        int downGreen = 0;
        int downBlue = 0;
        for (int i = 1; i < checkNearPixel; i++) {
            Object data1 = image.getRaster().getDataElements(x, y + i, null);
            int dataRed1 = image.getColorModel().getRed(data1);
            int dataBlue1 = image.getColorModel().getBlue(data1);
            int dataGreen1 = image.getColorModel().getGreen(data1);
            downRedCount += dataRed1;
            downBlue += dataBlue1;
            downGreen += dataGreen1;
        }
        if ((Math.abs(upRedCount - downRedCount) +
                Math.abs(upGreen - downGreen) +
                Math.abs(upBlue - downBlue) > colorMinDiff)) {
            return true;
        }
        return false;
    }

    /**
     * @param bufferedImage:
     * @return java.util.List<java.lang.Integer> y轴的两个值
     * @author HXH
     * @description: 识别图片的中，身份证y轴边缘
     * @date 2024/3/1
     **/
    public static List<Integer> getIDCardY(BufferedImage bufferedImage) {
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        System.out.println("图片宽度：" + width);
        System.out.println("图片高度" + height);

//        long begin = System.currentTimeMillis();

        int hitYCount = 0;
        //连续y个像素都是边缘，则认为就是y这一行就是边缘
        int hitYMinCount = width / 2 / 40;
        hitYMinCount = Math.max(40, hitYMinCount);
        System.out.println("hitYMinCount: " + hitYMinCount);

        List<Integer> yEdge = new ArrayList<>();

        int maxWidth = width - checkNearPixel;
        //这个4是识别时，每隔4个像素点识别一次
        //这个应该比checkNearPixel大，否则会重复计算，耗时不讨好
        for (int y = checkNearPixel, maxHeight = height - checkNearPixel; y < maxHeight; y += 2) {
            //这个10与身份证在图片中的倾斜角度有关，身份证越倾斜，这个值需要越小，耗时越长
            //但是也要考虑到后面身份证识别时，如果倾角过大，可能截取失败
            //如果倾角过大，ocr识别失败
            for (int x = checkNearPixel; x < maxWidth; x += 5) {
                if (getIDCardYCheck(bufferedImage, x, y)) {
                    hitYCount++;
                    //累计命中检测次数达到阈值，加到边缘候选项
                    if (hitYCount > hitYMinCount) {
                        yEdge.add(y);
                        //System.out.println("边缘检测....y:" + y + "   x:" + x);
                    }
                } else {
                    hitYCount = 0;
                }

            }
        }

        //置信度 -》 实际y轴
        Map<Integer, Integer> confidence2Y = new HashMap<>();
        int confidence = 0;
        int confidenceY = yEdge.get(0);
        int maxCountConfidence = Math.min(width / 90,100);
        for (int i = 1; i < yEdge.size(); i++) {
            int temp = yEdge.get(i);
            //100像素的以内，归为同一y轴值
            if (temp - confidenceY <= maxCountConfidence) {
                confidence++;
            } else {
                System.out.println("边缘y:" + confidenceY + " 置信度：" + confidence);
                confidence2Y.put(confidenceY, confidence);
                confidenceY = temp;
                confidence = 0;
            }
        }
        confidence2Y.put(confidenceY, confidence);
//        long end = System.currentTimeMillis();
        System.out.println("边缘y:" + confidenceY + " 置信度：" + confidence);


        List<Integer> res = new ArrayList<>(2);
        List<Integer> keys = new ArrayList<>(confidence2Y.values());
        keys.sort((a, b) -> b - a);
        keys = keys.subList(0, 2);
        for (Integer integer : confidence2Y.keySet()) {
            for (int i = 0; i < keys.size(); i++) {
                if (confidence2Y.get(integer).equals(keys.get(i))) {
                    res.add(integer);
                    break;
                }
                if (res.size() >= 2) {
                    break;
                }
            }
            if (res.size() >= 2) {
                break;
            }
        }
        res.sort(Comparator.comparingInt(a -> a));
        System.out.println("识别身份证y轴位置：" + res.get(0));
        System.out.println("识别身份证y轴位置：" + res.get(1));
        return res;
    }


    //边缘检测算法，好像不适用
    @Deprecated
    public static void checkEdge(String text, String path) throws IOException {
        int size = 0;
        //根据不同请求调用不同的处理方法
        if (text.equals("Roberts边缘检测")) size = 2;
        if (text.equals("Sobel边缘检测")) size = 3;
        if (text.equals("Prewitt边缘检测")) size = 3;
        if (text.equals("Krisch边缘检测")) size = 3;
        if (text.equals("Laplace边缘检测")) size = 3;
        //设置算子的卷积核
        //Roberts算子卷积核
        double[][] robertsX = {{1, 0}, {0, -1}};
        double[][] robertsY = {{0, 1}, {-1, 0}};
        //Sobel算子卷积核
        double[][] sobelX = {{1, 0, -1}, {2, 0, -2}, {1, 0, -1}};
        double[][] sobelY = {{1, 2, 1}, {0, 0, 0}, {-1, -2, -1}};
        //Prewitt算子卷积核
        double[][] prewittX = {{-1, 0, 1}, {-1, 0, 1}, {-1, 0, 1}};
        double[][] prewittY = {{1, 1, 1}, {0, 0, 0}, {-1, -1, -1}};
        //Krisch算子卷积核
        double[][] krischN = {{5, 5, 5}, {-3, 0, -3}, {-3, -3, -3}};
        double[][] krischNE = {{-3, 5, 5}, {-3, 0, 5}, {-3, -3, -3}};
        double[][] krischE = {{-3, -3, 5}, {-3, 0, 5}, {-3, -3, 5}};
        double[][] krischSE = {{-3, -3, -3}, {-3, 0, 5}, {-3, 5, 5}};
        double[][] krischS = {{-3, -3, -3}, {-3, 0, -3}, {5, 5, 5}};
        double[][] krischSW = {{-3, -3, -3}, {5, 0, -3}, {5, 5, -3}};
        double[][] krischW = {{5, -3, -3}, {5, 0, -3}, {5, -3, -3}};
        double[][] krischNW = {{5, 5, -3}, {5, 0, -3}, {-3, -3, -3}};
        //Laplace算子卷积核
        double[][] laplace = {{1, 1, 1}, {1, -8, 1}, {1, 1, 1}};
        //首先将图片灰度化
//        toGray();

        BufferedImage bufferedImage = ImageIO.read(new File(path));
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();

        int[][] gray = new int[width][height];
        for (int x = bufferedImage.getMinX(); x < width; x++) {
            for (int y = bufferedImage.getMinY(); y < height; y++) {
                int color = bufferedImage.getRGB(x, y);
                gray[x][y] = color;
            }
        }

        BufferedImage after = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D graphics = after.createGraphics();

        //下面代码中width代表图片宽度，height代表图片高度，gray为图片的灰度数组，存储的是每个像素点的灰度值
        //前三个算子请仔细读第一个算子的代码，之后的是一样的
        if (text.equals("Roberts边缘检测")) {
            for (int x = 0; x < width - size + 1; x++) {
                for (int y = 0; y < height - size + 1; y++) {
                    //设置x,y方向的结果变量，一定要在循环内初始化，因为每次循环都要清零重新加
                    int tempX = 0;
                    int tempY = 0;
                    //对size*size区域进行卷积操作
                    for (int i = 0; i < size; i++) {
                        for (int j = 0; j < size; j++) {
                            tempX += gray[x + i][y + j] * robertsX[i][j];
                            tempY += gray[x + i][y + j] * robertsY[i][j];
                        }
                    }
                    //求梯度值
                    int result = (int) Math.sqrt(tempX * tempX + tempY * tempY);
                    //设置阈值
                    int RMax = 230;
                    //根据阈值设置黑白度
                    if (result > RMax) result = 255;
                    if (result <= RMax) result = 0;
                    //设置颜色来描点
                    Color color = new Color(result, result, result);
                    graphics.setColor(color);
                    graphics.drawLine(x + size / 2, y + size / 2, x + size / 2, y + size / 2);
                }
            }
        }
        if (text.equals("Sobel边缘检测")) {
            for (int x = 0; x < width - size + 1; x++) {
                for (int y = 0; y < height - size + 1; y++) {
                    int tempX = 0;
                    int tempY = 0;
                    for (int i = 0; i < size; i++) {
                        for (int j = 0; j < size; j++) {
                            tempX += gray[x + i][y + j] * sobelX[i][j];
                            tempY += gray[x + i][y + j] * sobelY[i][j];
                        }
                    }
                    int result = (int) Math.sqrt(tempX * tempX + tempY * tempY);
                    //设置阈值
                    int GMax = 50;

                    if (result > GMax) result = 255;
                    if (result <= GMax) result = 0;

                    Color color = new Color(result, result, result);
                    graphics.setColor(color);
                    graphics.drawLine(x + size / 2, y + size / 2, x + size / 2, y + size / 2);
                }
            }
        }
        if (text.equals("Prewitt边缘检测")) {
            for (int x = 0; x < width - size + 1; x++) {
                for (int y = 0; y < height - size + 1; y++) {
                    int tempX = 0;
                    int tempY = 0;
                    for (int i = 0; i < size; i++) {
                        for (int j = 0; j < size; j++) {
                            tempX += gray[x + i][y + j] * prewittX[i][j];
                            tempY += gray[x + i][y + j] * prewittY[i][j];
                        }
                    }
                    int result = (int) Math.sqrt(tempX * tempX + tempY * tempY);
                    //设置阈值
                    int PMax = 254;

                    if (result > PMax) result = 255;
                    if (result < PMax) result = 0;

                    Color color = new Color(result, result, result);
                    graphics.setColor(color);
                    graphics.drawLine(x + size / 2, y + size / 2, x + size / 2, y + size / 2);
                }
            }
        }
        if (text.equals("Krisch边缘检测")) {
            for (int x = 0; x < width - size + 1; x++) {
                for (int y = 0; y < height - size + 1; y++) {
                    //设置一个数组存储八个方向的值,按顺时针方向从北极开始
                    int[] temp = {0, 0, 0, 0, 0, 0, 0, 0};
                    //对size*size区域进行卷积操作
                    for (int i = 0; i < size; i++) {
                        for (int j = 0; j < size; j++) {
                            temp[0] += gray[x + i][y + j] * krischN[i][j];
                            temp[1] += gray[x + i][y + j] * krischNE[i][j];
                            temp[2] += gray[x + i][y + j] * krischE[i][j];
                            temp[3] += gray[x + i][y + j] * krischSE[i][j];
                            temp[4] += gray[x + i][y + j] * krischS[i][j];
                            temp[5] += gray[x + i][y + j] * krischSW[i][j];
                            temp[6] += gray[x + i][y + j] * krischW[i][j];
                            temp[7] += gray[x + i][y + j] * krischNW[i][j];
                        }
                    }
                    ;
                    //找出八个方向的最大值（代码为数组列表求最大值）
                    int result = Arrays.stream(temp).max().getAsInt();
                    //若是求得结果超出灰度值的0-255范围，将其设成最大值或最小值
                    if (result > 255) result = 255;
                    if (result < 0) result = 0;
                    //画图
                    Color color = new Color(result, result, result);
                    graphics.setColor(color);
                    graphics.drawLine(x + size / 2, y + size / 2, x + size / 2, y + size / 2);
                }
            }
        }
        if (text.equals("Laplace边缘检测")) {
            for (int x = 0; x < width - size + 1; x++) {
                for (int y = 0; y < height - size + 1; y++) {
                    int result = 0;
                    //对size*size区域进行卷积操作
                    for (int i = 0; i < size; i++) {
                        for (int j = 0; j < size; j++) {
                            result += gray[x + i][y + j] * laplace[i][j];
                        }
                    }
                    //设置阈值
                    int LMax = 254;
                    //根据阈值设置黑白度
                    if (result > LMax) result = 255;
                    if (result < LMax) result = 0;
                    //画图
                    Color color = new Color(result, result, result);
                    graphics.setColor(color);
                    graphics.drawLine(x + size / 2, y + size / 2, x + size / 2, y + size / 2);
                }
            }
        }

        ImageIO.write(after, "jpg", new FileOutputStream("C:\\Users\\lenovo\\Desktop\\orcPicture\\after\\aa.jpg"));
    }

}